
package com.jf.cloud.multishop.listener;

import com.jf.cloud.api.feign.SearchOrderFeignClient;
import com.jf.cloud.api.order.feign.OrderFeignClient;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.bo.PayNotifyBO;
import com.jf.cloud.common.order.vo.OrderSimpleAmountInfoBO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.rocketmq.config.RocketMqConstant;
import com.jf.cloud.common.vo.ShopSubstituteSalesVO;
import com.jf.cloud.multishop.service.ShopSubstituteSalesService;
import com.jf.cloud.multishop.service.ShopWalletService;
import com.jf.cloud.multishop.vo.ShopWalletVO;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zz
 */
@Component
@RocketMQMessageListener(topic = RocketMqConstant.ORDER_PURCHASE_NOTIFY_SHOP_TOPIC,consumerGroup = RocketMqConstant.ORDER_PURCHASE_NOTIFY_SHOP_TOPIC)
public class OrderPurchaseNotifyShopConsumer implements RocketMQListener<PayNotifyBO> {

    @Autowired
    private ShopWalletService shopWalletService;

    @Autowired
    private ShopSubstituteSalesService shopSubstituteSalesService;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private SearchOrderFeignClient searchOrderFeignClient;


    /**
     * 订单支付成功 分账
     */
    @Override
    public void onMessage(PayNotifyBO message) {

        ServerResponseEntity<List<OrderSimpleAmountInfoBO>> ordersShopWalletInfoResponse = orderFeignClient.getOrdersSimpleAmountInfo(message.getOrderIds());
        if (!ordersShopWalletInfoResponse.isSuccess()) {
            throw new LuckException(ResponseEnum.EXCEPTION);
        }
        List<OrderSimpleAmountInfoBO> orderShopWalletInfos = ordersShopWalletInfoResponse.getData();
        List<Long> shopIds = orderShopWalletInfos.stream().map(OrderSimpleAmountInfoBO::getShopId).collect(Collectors.toList());
        // 获取店铺已结算金额map
        List<ShopWalletVO> shopWalletList = shopWalletService.listByShopIds(shopIds);
        Map<Long, Long> settledAmountMap = shopWalletList.stream().collect(Collectors.toMap(ShopWalletVO::getShopId, ShopWalletVO::getSettledAmount));
        // 根据shopIds获取商家的代销配置
        List<ShopSubstituteSalesVO> shopSubstituteSalesList = shopSubstituteSalesService.listByShopIds(shopIds);
        Map<Long, Integer> salesMap = shopSubstituteSalesList.stream().collect(Collectors.toMap(ShopSubstituteSalesVO::getShopId, ShopSubstituteSalesVO::getOrderShape));
        shopWalletService.addAmountByOrder(orderShopWalletInfos, message,settledAmountMap,salesMap);
    }
}
